package com.fengwuj.tkmybatisdemo.controller;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.elasticsearch.indices.DeleteIndexResponse;
import co.elastic.clients.elasticsearch.indices.GetIndexResponse;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import com.fengwuj.tkmybatisdemo.esentity.BlogModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/")
public class EsTestController {

    @Autowired
    private ElasticsearchClient client;

    @PostMapping("/index/{indexName}")
    public CreateIndexResponse addIndex(@PathVariable String indexName) throws IOException {
        return client.indices().create(c -> c.index(indexName));
    }

    @DeleteMapping("/index/{indexName}")
    public DeleteIndexResponse deleteIndex(@PathVariable String indexName) throws IOException {
        return client.indices().delete(c -> c.index(indexName));
    }

    @GetMapping("/index/{indexName}")
    public GetIndexResponse getIndex(@PathVariable String indexName) throws IOException {
        return client.indices().get(c -> c.index(indexName));
    }

    @GetMapping("/index/{indexName}/exist")
    public BooleanResponse existIndex(@PathVariable String indexName) throws IOException {
        return client.indices().exists(c -> c.index(indexName));
    }

    @PostMapping("/index/{indexName}/data")
    public void addData(@PathVariable String indexName,
                        @RequestBody BlogModel blogModel) throws IOException {
        blogModel.setId(UUID.randomUUID().toString());
        client.create(i -> i.id(blogModel.getId()).index(indexName).document(blogModel));
    }

    @GetMapping("/index/{indexName}/data")
    public List<BlogModel> list(@PathVariable String indexName, String myTitle) throws IOException {
        SearchResponse<BlogModel> blogModels = client.search(sq -> sq.index(indexName)
                .query(q ->
                        q.term(t -> t.field("myTitle.keyword").value(v -> v.stringValue(myTitle)))),
                BlogModel.class);
        return blogModels.hits().hits().stream().map(Hit::source).collect(Collectors.toList());
    }
}
